package jjn.daily;

import java.util.Scanner;

/**
 * @author Jjn
 * @since 2023/8/24 23:31
 */
public class LeetCode309 {
    public int maxProfit(int[] prices) {
        // 状态包含：持股/卖出且冷冻/卖出非冷冻
        int[][] dp = new int[prices.length][3];
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        dp[0][2] = 0;
        for (int i = 1; i < prices.length; i++) {
            // dp[i][0] - 持有股票
            // 1.保留昨天买的股票
            // 2. 卖出非冷冻期的股票
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][2] - prices[i]);
            // dp[i][1]
            // 卖出昨天购买的股票
            dp[i][1] = dp[i - 1][0] + prices[i];
            // dp[i][2]
            // 1.昨天卖出,非冷冻
            // 2. 昨天没卖出，非冷冻
            dp[i][2] = Math.max(dp[i - 1][1], dp[i - 1][2]);
        }
        // 若最后一天依然持有股票,显然不是最佳解
        return Math.max(dp[prices.length - 1][1], dp[prices.length - 1][2]);
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int total = scanner.nextInt();
        int[] prices = new int[total];
        for (int i = 0; i < total; i++) {
            prices[i] = scanner.nextInt();
        }
        int maxProfit = new LeetCode309().maxProfit(prices);
        System.out.println(maxProfit);
    }
}
